package com.example.appalumaj;

import java.io.IOException;
import java.net.UnknownHostException;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;

import android.annotation.SuppressLint;
import android.net.Uri;
import android.os.Build;
import android.os.StrictMode;
import android.util.Log;
import android.widget.Toast;

public class ServicioFotos {
		
	@SuppressLint("NewApi")
	public ArrayList<Uri> dameFotos(int carpeta) {

		if (Build.VERSION.SDK_INT > 10) {
			StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
					.permitAll().build();
			StrictMode.setThreadPolicy(policy);
		}
		
		try {
		
		String respStr = "";
		ArrayList<Uri> urls = new ArrayList<Uri>();
		
		HttpClient httpClient = new DefaultHttpClient();
		HttpGet peticion = new HttpGet(
				"http://www.alumaj.es/SubeFotos.php/json/?cpt="+carpeta);
		peticion.setHeader("content-type", "application/json");

		
			HttpResponse resp = httpClient.execute(peticion);
			respStr = EntityUtils.toString(resp.getEntity());
			
			String[] tempo = respStr.split("%&");
			
			for (int i = 0; i < tempo.length; i++) {
				urls.add(Uri.parse(tempo[i]));
			}
			
			return urls;
		} catch (UnknownHostException ex) {
			Log.e("ServicioRest", "Error!", ex);
			return null;
		} catch (ParseException e) {
			Log.e("ServicioRest", "Error!", e);
			return null;
		} catch (IOException e) {
			Log.e("ServicioRest", "Error!", e);
			return null;
		}
	}
	
	public boolean borraFoto(Uri url){
		
		HttpClient httpClient = new DefaultHttpClient();
		HttpDelete peticion = new HttpDelete(
				"http://www.alumaj.es/SubeFotos.php/json/?url="+url);
		peticion.setHeader("content-type", "application/json");
		
		try {
			HttpResponse resp = httpClient.execute(peticion);
			
			String respStr = EntityUtils.toString(resp.getEntity());
			
			if(respStr.equalsIgnoreCase("1")){
				return true;
			} else {
				Log.i("Delete no", respStr);
				return false;
			}
		} catch (UnknownHostException ex) {
			Log.e("ServicioRest", "Error!", ex);
			return false;
		} catch (ParseException e) {
			Log.e("ServicioRest", "Error!", e);
			return false;
		} catch (IOException e) {
			Log.e("ServicioRest", "Error!", e);
			return false;
		}
	}

}
